using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Mite.Configuration;
using Mite;
using NAnt.Core.Attributes;



namespace Mite.BuildTask
{
    public interface IMigrationTask
    {
        string SelectedEnvironment { get; set; }
        string MigrationDirectory { get; set; }
        string EnvironmentSettingsFilePath { get; set; }
    }

    public static class TaskExtensionMethods
    {
        public static bool Migrate(this IMigrationTask task)
        {
            DirectoryInfo dir;
            DirectoryInfo db;
            if (string.IsNullOrEmpty(task.MigrationDirectory))
            {
                dir = new DirectoryInfo(Environment.CurrentDirectory);
                if (dir.Parent != null)
                {
                    var dirs = dir.Parent.GetDirectories();
                    db = dirs.SingleOrDefault(x => x.Name == "migrations");
                    if (db == null)
                    {
                        throw new DirectoryNotFoundException("Directory titled 'migrations' not found in " + dir.FullName);
                    }
                }
                else
                {
                    throw new Exception("Directory has no parent");
                }
            }
            else
            {
                db = new DirectoryInfo(task.MigrationDirectory);
            }

            string settingsPath;
            if (string.IsNullOrEmpty(task.EnvironmentSettingsFilePath))
                settingsPath = new DirectoryInfo(db.Parent.FullName) + "settings.boo";
            else
                settingsPath = task.EnvironmentSettingsFilePath;
            if (!File.Exists(settingsPath))
                throw new FileNotFoundException("settings.boo file not found in the root in "+settingsPath);

            Settings.Load(settingsPath);
            MiteEnvironment me = Settings.GetEnvironment(task.SelectedEnvironment);
        	Migrator.MigrateTo(me,null, task.MigrationDirectory);
            return true;
        }
    }
}